package com.sinoglobal.dumping.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sinoglobal.dumping.R;
import com.sinoglobal.dumping.activity.Dumpling_MainActivity;
import com.sinoglobal.dumping.api.Dumpling_RemoteImpl;
import com.sinoglobal.dumping.base.Dumpling_SinoAsyncTask;
import com.sinoglobal.dumping.base.Dumpling_SinoBaseActivity;
import com.sinoglobal.dumping.base.Dumpling_SinoBaseFragment;
import com.sinoglobal.dumping.base.Dumpling_SinoConstans;
import com.sinoglobal.dumping.bean.Dumpling_LogOutAcquireDumplingBean;
import com.sinoglobal.dumping.bean.Dumpling_LogOutMaxDumplingCountBean;
import com.sinoglobal.dumping.bean.Dumpling_TimeAction;
import com.sinoglobal.dumping.fragment.helper.Dumpling_HomefragmentImpl;
import com.sinoglobal.dumping.fragment.helper.Dumpling_IHomeFragmentHelper;
import com.sinoglobal.dumping.util.DumplingUtils;
import com.sinoglobal.dumping.util.Dumpling_HttpMethodSet;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import static com.sinoglobal.dumping.base.Dumpling_SinoConstans.DUMPLING_COUNT;
import static com.sinoglobal.dumping.base.Dumpling_SinoConstans.LOGIN_STATE_LOGOUT;
import static com.sinoglobal.dumping.base.Dumpling_SinoValueManager.clearAllDumpling;
import static com.sinoglobal.dumping.base.Dumpling_SinoValueManager.putValue;
import static com.sinoglobal.dumping.util.DumplingUtils.getCode;

/**
 * Created by KeZhuang on 2015/10/29.
 */
@SuppressLint("HandlerLeak")
public class Dumpling_HomeFragment extends Dumpling_SinoBaseFragment implements
        Dumpling_SinoBaseActivity.OnLogInListener, Dumpling_HttpMethodSet.OnGetMoneyListener {
    public Dumpling_IHomeFragmentHelper helper;
    public ImageView topBanner;                                     //勺子和底部banner和顶部banner
    public ImageView ivDumpling;                                       //饺子图片
    public TextView  text3;                  //继续加油提示语/剩余饺子总数/领取提示语/窗帘上的提示语
    public Dumpling_LogOutAcquireDumplingBean acquireDumplingBean;     //捞取饺子实体类
    public Dumpling_MainActivity parentActivity;                       //activity变量
    public static final boolean DEBUG = false;                          //本类的debug标识
    private int timeSpace = 1000 * 60;                                    //定时任务的间隔时间
    private boolean isActionStart = true;                               //是否开启定时查询
    private Timer mTimer;                                               //定时任务
    private TimerTask mTimerTask;                                       //定时队列
    public LinearLayout llTimeLine;                                   //时间线：父布局
    public TextView tvLineLefttop;                                     //时间线：左上文字
    public TextView tvLineLeftbottom;                                  //时间线：左下文字
    public TextView tvLineCentertop;                                   //时间线：中上文字
    public TextView tvLineCenterbottom;                                //时间线：中下文字
    public TextView tvLineRighttop;                                    //时间线：右上文字
    public TextView tvLineRightbottom;                                 //时间线：右下文字
    public boolean isShowActviity;                                     //显示是否是当前activity
    private View rootView;                                              //缓存fragment的view

    @Override
    public void onAttach(Activity context) {
        super.onAttach(context);
        helper = new Dumpling_HomefragmentImpl(this);
        Dumpling_HttpMethodSet.setOnGetMoneyListener(this);
    }

    public Dumpling_LogOutAcquireDumplingBean getAcquireDumplingBean() {
        return acquireDumplingBean;
    }

    public void setAcquireDumplingBean(Dumpling_LogOutAcquireDumplingBean acquireDumplingBean) {
        this.acquireDumplingBean = acquireDumplingBean;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if(rootView==null){
            rootView = inflater.inflate(R.layout.dumpling_home_fragment, null);
        }
        if(rootView.getParent()!=null){
            ((ViewGroup)rootView.getParent()).removeView(rootView);
        }
        return rootView;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        helper.onViewCreate(view);
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        helper.onActivityCreate();
        helper.queryDumplingMaxCount();
        queryLoginOutCount(false, true);
        addAcquireDumplingNum();
        executeTask();
    }

    /**
     * 初始化捞取次数
     */
    public void addAcquireDumplingNum() {
        if (!Dumpling_SinoBaseActivity.isNoLogIn(parentActivity)) {
            addTask(Dumpling_HttpMethodSet.addAcquireDunmplingNum(getActivity(), Dumpling_SinoConstans.USER_ID));
        }
    }
    /**
     * 查询未登录的最大捞取次数
     */
    public void queryLoginOutCount(boolean isCannable, boolean isShowing) {
        addTask(new Dumpling_SinoAsyncTask<Object, Void, Dumpling_LogOutMaxDumplingCountBean>(parentActivity, isCannable, isShowing) {

            @Override
            public Dumpling_LogOutMaxDumplingCountBean before(Object... params) throws Exception {
                return Dumpling_RemoteImpl.getInstance().queryLogoutCount();
            }

            @Override
            public void after(Dumpling_LogOutMaxDumplingCountBean resultList) {
                if (resultList != null) {
                    if (Dumpling_SinoConstans.SUCCESS_CODE == resultList.getCode()) {
                        if (resultList.getResultList().getCount() != null) {
                            int acquireCount = Integer.parseInt(resultList.getResultList().getCount());
                            if (getCode(parentActivity) == 0 || getCode(parentActivity) == Dumpling_SinoConstans.SUCCESS_CODE) {
                                putValue(parentActivity, DUMPLING_COUNT, acquireCount, true);
                            }
                        }
                    }
                }
            }

            @Override
            public void exception() {

            }
        });
    }

    public long getMaxCount(){
        return ((Dumpling_HomefragmentImpl)helper).getMaxDumplingCount();
    }

    public Dumpling_IHomeFragmentHelper getHelper() {
        return helper;
    }

    public void onAntiViolence(View v) {
        helper.onButtonClick(v);
    }

    @Override
    public void onStop() {
        super.onStop();
        isShowActviity =false;
        helper.cancelAnimation();
    }

    public boolean isShowActviity() {
        return isShowActviity;
    }

    @Override
    public void onResume() {
        super.onResume();
        isShowActviity = true;
        ivDumpling.setVisibility(View.GONE);
        helper.checkNetWork();
        helper.queryDumplingMaxCount();
        helper.setUpTip();
        helper.managerRandom();
    }

    /**
     * 获取活动内容
     * 活动开启方式为通过某个接口返回的状态值进行判定
     */
    public void getActionContent() {

        new Dumpling_SinoAsyncTask<Object, Void, Dumpling_TimeAction>(parentActivity, false, false) {

            @Override
            public Dumpling_TimeAction before(Object... params) throws Exception {
                return Dumpling_RemoteImpl.getInstance().getTimeAxis();
            }

            @Override
            public void after(Dumpling_TimeAction dumpling_timeAction) {
                if (dumpling_timeAction != null) {
                    if (dumpling_timeAction.getCode() == Dumpling_SinoConstans.SUCCESS_CODE) {
                        if (dumpling_timeAction.getResultList() != null && dumpling_timeAction.getResultList().size() >= 3) {
                            setActionUI(dumpling_timeAction.getResultList());
                            startActionTask();
                        }
                    } else {
                        setActionUI(null);
                        recycleTask();
                    }
                }
            }

            @Override
            public void exception() {

            }
        }.execute();

    }

    /**
     * 启动活动定时任务
     */
    private void startActionTask() {
        if (isActionStart) {
            initActionTask();
            mTimer.schedule(mTimerTask, timeSpace, timeSpace);
            isActionStart = false;
        }
    }

    /**
     * 活动定时相关
     */
    private void initActionTask() {
        mTimer = new Timer();
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                Message msg = mHandler.obtainMessage();
                msg.what = 1;
                mHandler.sendMessage(msg);
            }
        };
    }


    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int tag = msg.what;
            if (tag == 1) {
                getActionContent();
            }
        }
    };
    public String actionTimeOfDay(String time) {
        // if (Dumpling_TextUtil.stringIsNull(time)) {
        // return "";
        // }
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        long t = Long.valueOf(time);
        String data = sdf.format(t*1000);
        return data;
    }
    /**
     * 设置活动UI：非空：活动存在，topBanner隐藏；空：活动不存在，topBanner显示
     *
     * @param actionList
     */
    public void setActionUI(ArrayList<Dumpling_TimeAction.Dumpling_TimeAction_Content> actionList) {
        if (actionList != null) {
            llTimeLine.setVisibility(View.VISIBLE);
            topBanner.setVisibility(View.GONE);
            if(actionList.get(0)!=null){
                if(actionList.get(0).getPot().length() > 0){
                    tvLineLefttop.setText(actionList.get(0).getPot() + "\t");
                }else{
                    tvLineLefttop.setText("");
                }
                tvLineLefttop.append(actionTimeOfDay(actionList.get(0).getTime()));
                tvLineLeftbottom.setText(actionList.get(0).getInfo());
            }

            if(actionList.get(1)!=null){
                if(actionList.get(1).getPot().length() > 0){
                    tvLineCentertop.setText(actionList.get(1).getPot() + "\t");
                }else{
                    tvLineCentertop.setText("");
                }
                tvLineCentertop.append(actionTimeOfDay(actionList.get(1).getTime()));
                tvLineCenterbottom.setText(actionList.get(1).getInfo());
            }

            if(actionList.get(2)!=null){
                if(actionList.get(2).getPot().length() > 0){
                    tvLineRighttop.setText(actionList.get(2).getPot() + "\t");
                }else{
                    tvLineRighttop.setText("");
                }
                tvLineRighttop.append(actionTimeOfDay(actionList.get(2).getTime()));
                tvLineRightbottom.setText(actionList.get(2).getInfo());
            }
            
        } else {
            llTimeLine.setVisibility(View.GONE);
            topBanner.setVisibility(View.VISIBLE);
        }

    }

    /**
     * 停止定时任务
     */
    public void recycleTask() {
        if (mTimer != null && mTimerTask != null) {
            mTimerTask.cancel();
            mTimer.cancel();
            mTimerTask = null;
            mTimer = null;
        }
    }

    @Override
    public void onLogInListener() {
        int acquireCount = DumplingUtils.getCount(parentActivity);
        acquireCount++;
        putValue(getActivity(), DUMPLING_COUNT, acquireCount, true);
    }

    @Override
    public void onGetMoney(int code) {
        if (code != Dumpling_SinoConstans.SUCCESS_CODE) {
            text3.setVisibility(View.VISIBLE);
        } else {
            rootView.findViewById(R.id.text_1).setVisibility(View.GONE);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        recycleTask();
        clearTask();
        if(mHandler!=null){
            mHandler.removeCallbacksAndMessages(null);
        }
        ((Dumpling_SinoBaseActivity) getActivity()).unregisterLogInListener(Dumpling_HomeFragment.class.getName());
        helper.cancelRandom();
        if(DumplingUtils.getLogin(parentActivity)==LOGIN_STATE_LOGOUT){
            if(getCode(parentActivity)==0 || getCode(parentActivity)==Dumpling_SinoConstans.SUCCESS_CODE){
                clearAllDumpling(parentActivity);
            }
        }
    }


}